package com.pos.widgets;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

public abstract class AbsAdapter<T> extends BaseAdapter {

	private Context context;
	private List<T> datas;
	private int layoutId;   //item布局资源的id标识

	
	public AbsAdapter(Context context, List<T> datas, int layoutId ) {
		this.context = context;
		this.datas = datas;
		this.layoutId = layoutId;

	}

	@Override
	public int getCount() {
		return datas.size();
	}

	@Override
	public T getItem(int arg0) {     //返回数据源中指定位置的数据
		return datas.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {    //返回数据源中指定位置的数据的id
		return arg0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder vHolder = null;
		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(layoutId, parent,false);
			
			vHolder = new ViewHolder(convertView);
			convertView.setTag(vHolder);
		}else {
			vHolder = (ViewHolder) convertView.getTag();
		}
		
		showData(vHolder, getItem(position) ,position);//显示数据
		
		return convertView;
	}

	
	public abstract void showData(ViewHolder vHolder, T data,  int position);
	
	
	public static class ViewHolder{
		private SparseArray<View> cacheViews;
		private View itemView;       //item的布局对象
		
		public ViewHolder(View itemView){
			this.itemView = itemView;
			cacheViews = new SparseArray<View>();
		}
		
		public View getView(int id){
			View view = cacheViews.get(id);
			if (view == null) {//缓存不存在
				view = itemView.findViewById(id);
				if (view != null) {
					//将已查到的空间存放在空间缓存中，以备下次查找，而不需要再次调用FindViebyId（）查找
					cacheViews.put(id, view);
				}
			}
			return view;
		}
		
	}
}
